﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCFAuthorization.Contract;

namespace WCFAuthorization.Service
{
    public class Service : IContract
    {

        public CheckResult CheckUser(string name)
        {
            CheckResult result = new CheckResult();
            var query = Cacher.UsersCache
                .Where(p => p.UserName.Equals(name));
            if (query.Count() > 0)
            {
                User pUser = query.FirstOrDefault();
                if (!pUser.Enable)
                {
                    result.IsValid = false;
                    result.Context = "用户被禁止使用!";
                    return result;
                }
                if (pUser.ExpiredTime <= DateTime.Now)
                {
                    result.IsValid = false;
                    result.Context = "用户已过期!";
                    return result;
                }
                result.IsValid = true;
                result.Context = string.Format("剩余使用天数:{0}",
                    pUser.ExpiredTime.Subtract(DateTime.Now).Days);
            }
            else
            {
                result.IsValid = false;
                result.Context = "验证失败,用户不存在!";
            }
            return result;
        }


        public void Upload(string text)
        {
            Console.WriteLine(text);
        }

        public string GetValid(string args)
        {
            string tm = Convert.ToBase64String(Encoding.Default.GetBytes(GetUtcTime()));
            return string.Format("ua={0}|ma=VJpK1iWRUo0=|br=cT0uW9fzK/9XRVDMdH+1w4wW+DUjWjQR|pr=VJpK1iWRUo0=|id=VJpK1iWRUo0=|mc=VtEP031H7lxve2vwbW7chVyzmXQNuAvhN5xLn05XFgE=|ks=+iyYeBhfRhieJBRrKJOJOXwpQCu/tSD2eeJlkc+kaiVfozW2zDN1A7wowUlBMKfoKdYddwYFIwrpiKEAlXOqhTSr8xiU6paQTU0dASu8PFhecSb9iWbztiH4XcS+ukSG",
                tm);
        }

        public static string GetUtcTime()
        {
            TimeSpan tspan = DateTime.Now - Convert.ToDateTime("1970-01-01");
            Int64 interval = Convert.ToInt64((tspan.TotalMilliseconds)) - 8 * 3600;
            return interval.ToString();
        }
    }
}